<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
		<uni-forms-item name="url" label="壁纸" required>
			<upload-image randomFileName cloudPath="communityshare"  ref="uploadImage" :maxSize="4" v-model="formData.url" ></upload-image>
		</uni-forms-item>
      <!-- <uni-forms-item name="url" label="" required>
        <uni-easyinput placeholder="图片地址" v-model="formData.url"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="desc" label="描述" required>
        <uni-easyinput	 autoHeight :trim="true"  type="textarea"  placeholder="请描述一下壁纸，仅用于搜索时检索，不会展示" v-model="formData.desc"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="direction" label="方向" required>
        <uni-data-checkbox selectedColor="#32DBBA" selectedTextColor="#32DBBA" v-model="formData.direction" :localdata="formOptions.direction_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" @click="submit">提交</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/wallpaper-userShare.js';
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
  import CrossFileReader from '@/utils/CrossFileReader.js'
  import CryptoJS from "crypto-js"; 
  const cloudUtilsObj = uniCloud.importObject("wallpaper-utils")
  const db = uniCloud.database();
  const dbCollectionName = 'wallpaper-userShare';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.indexOf(key) > -1) {
        result[key] = validator[key]
      }
    }
	// console.log(result);
    return result
  }

  

  export default {
    data() {
      let formData = {
        "desc": "",
        "url": "",
        "direction": null,
		"username": store.userInfo.username
      }
      return {
		  styles:{
			borderColor: '#32DBBA'
		  },  
        formData,
        formOptions: {
          "direction_localdata": [
            {
              "value": 0,
              "text": "横屏"
            },
            {
              "value": 1,
              "text": "竖屏"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 验证表单并提交
       */
      submit() {
		// 去除连续空格
		this.formData.desc = this.formData.desc.replace(/\s{3,}/g, '  ');
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then(async (res) => {
			let urlArr = []
			let md5Arr = []
			try{
				// 获取图片的md5
				const ArrayBufferArr = await CrossFileReader.readAsArrayBuffer(this.$refs.uploadImage.temFiles)
				
				md5Arr = ArrayBufferArr.map(item => {  
					Object.setPrototypeOf(item.result, ArrayBuffer.prototype);
					const wordArray = CryptoJS.lib.WordArray.create(item.result);
					return CryptoJS.MD5(wordArray).toString();
				})
				
				// console.log('#### md5Arr', md5Arr);
				// 是否已经存在 存在 true 不存在 false
				const isHasArr = await Promise.all(
				  md5Arr.map(async item => {
				    const regex = new RegExp(item, 'i'); 
				    const [res1, res2] = await Promise.all([
				      db.collection('wallpaper').where(`${regex}.test(md5)`).count(),
				      db.collection('wallpaper-userShare').where(`${regex}.test(md5)`).count()
				    ]);
				    return res1.result.total > 0 || res2.result.total > 0;
				  })
				);
				// console.log('#### isHasArr', isHasArr);
				const indexArr = [...isHasArr
				        .map((exists, index) => (exists ? index + 1 : null))
				        .filter(index => index !== null)]
				
				// console.log('#### indexArr', indexArr);
				const len = indexArr.length
				// console.log(len);
				if(md5Arr.length == 1 && len == 1){
					uni.showToast({
						icon: 'none',
						title: '壁纸在库中已存在'
					})
					return
				}else if(len != 0){
					uni.showToast({
						icon: 'none',
						title: `壁纸${indexArr.join('、')}在库中已存在`
					})
					return
				}else{
					// console.log("###### urlArr 0");
					// 校验通过后,上传图片到云存储 返回url数组
					urlArr = await this.$refs.uploadImage.goUpload()
					// console.log(urlArr);
				}
			}catch(e){
				console.log("#############",e);
				uni.showToast({
					title: '上传失败，请稍后重试',
					icon: 'none'
				})
				uni.hideLoading()
			}
			// Array.isArray(urlArr) ? null : urlArr = [urlArr]
			urlArr?.length ?  null : urlArr = [urlArr]
			// url存入要提交的表单
			// let newFormDataArr = []
			urlArr = urlArr.map((item, index)=>{
				// newFormDataArr.push({...this.formData, url:item, md5: md5Arr[index]})
				return {
					...this.formData,
					 url:item, 
					 md5: md5Arr[index]
				}
			})
			// 一次性存入
			return await this.submitForm(urlArr)
          // return this.submitForm(res)
        }).catch(() => {
			
        }).finally(() => {
          // uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            icon: 'none',
            title: '已提交审核'
          })
		  
          this.getOpenerEventChannel()?.emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .uni-container {
    padding: 15px;
  }
	:deep(){
		// uni-button {
		// 	background-color: $theme-bg-color2!important;
		// }
		.uni-button {
			background-color: $theme-bg-color2!important;
		}
		.is-focused {
			border-color: $theme-bg-color2!important;
		}
		.uni-data-checklist,.checklist-group{
			height: 100%;
		}
	
	}
  .uni-input-border,
  .uni-textarea-border {
    width: 100%;
    font-size: 14px;
    color: #666;
    border: 1px #e5e5e5 solid;
    border-radius: 5px;
    box-sizing: border-box;
  }

  .uni-input-border {
    padding: 0 10px;
    height: 35px;

  }

  .uni-textarea-border {
    padding: 10px;
    height: 80px;
  }

  .uni-button-group {
    margin-top: 50px;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
  }

  .uni-button {
    /* width: 184px; */
	width: 100%;
  }
</style>
